package com.peycard.vista;

import java.io.IOException;
import java.io.Serializable;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.validator.Email;
import org.hibernate.validator.Length;
import org.hibernate.validator.Max;
import org.hibernate.validator.Min;
import org.hibernate.validator.NotEmpty;
import org.hibernate.validator.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.peycard.common.PortalUserDTO;
import com.peycard.service.BaseService;
import com.peycard.util.Constantes;
import com.peycard.util.Utils;

@Controller(Constantes.BEAN_USUARIOS_PORTAL)
@Scope(Constantes.SCOPE_REQUEST)
public class UsuarioPortalControlador extends BaseController implements
		Serializable {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(UsuarioPortalControlador.class);
	private static final long serialVersionUID = 1L;
	private long idPortalUser;
	@NotEmpty
	@Length(min = 3, max = 20)
	private String firstName;
	@NotEmpty
	@Length(min = 3, max = 20)
	private String lastName;
	@NotEmpty
	private String user;
	private String password;
	private String passwordChanged;
	private String repeatPassword;
	@NotEmpty
	@Length(min = 1, max = 1)
	private String firstAccess;
	@NotEmpty
	@Email
	private String email;
	private String securityQuestion;
	@Length(min = 3, max = 20)
	private String answerQuestion;
	private String company;
	private String area;
	private String username;
	private String currentToken;
	@NotNull
	@Min(0)
	@Max(1)
	private int isActive;
	@NotEmpty
	private String rol;
	private String newIdPortalUser;
	@NotEmpty
	@Length(min = 3, max = 20)
	private String newFirstName;
	@NotEmpty
	@Length(min = 3, max = 20)
	private String newLastName;
	@NotEmpty
	private String newUser;
	@NotEmpty
	private String newPassword;
	@NotEmpty
	private String newRepeatPassword;
	@NotEmpty
	@Email
	private String newEmail;
	@NotEmpty
	private String newSecurityQuestion;
	@NotEmpty
	@Length(min = 3, max = 20)
	private String newAnswerQuestion;
	@NotEmpty
	private String newCompany;
	@NotEmpty
	private String newArea;
	@NotEmpty
	private String newUsername;
	@NotEmpty
	private String newFirstAcces;
	private Date newSaveData;
	@NotNull
	@Min(0)
	@Max(1)
	private int newIsActive;
	@NotEmpty
	private String newRol;
	private PortalUserDTO currentItem;
	private List<PortalUserDTO> listItems;

	public UsuarioPortalControlador() {
		currentToken = super.getTokenInContext();
		username = super.userLogged();
	}

	private void init() {
		try {
			BaseService service = new BaseService();
			service.setToken(currentToken);
			service.listISOMessage(Constantes.ISO003_PORTAL_USER_LIST,
					Constantes.PORTAL_USERNAME, username,
					Constantes.PORTAL_USER_LIST_KEY);
			List<String> userList = service.getList();
			if (service.getToken() != null && userList != null) {
				listItems = new ArrayList<PortalUserDTO>();

				for (int i = 0; i < userList.size(); i++) {
					String currentUser = userList.get(i);
					List<String> userData = Utils.convertList(currentUser);

					PortalUserDTO dto = new PortalUserDTO();
					long id = Long.valueOf(userData.get(0));
					dto.setIdPortalUser(id);
					dto.setFirstName(userData.get(1));
					dto.setLastName(userData.get(2));
					dto.setUser(userData.get(3));
					dto.setPassword(userData.get(4));
					dto.setEmail(userData.get(5));
					dto.setSecurityQuestion(userData.get(6));
					dto.setAnswerQuestion(userData.get(7));
					dto.setCompany(userData.get(8));
					dto.setArea(userData.get(9));
					dto.setIsActive(new Integer(userData.get(10)));
					dto.setRol(userData.get(11));
					listItems.add(dto);
				}
				super.setTokenInContext(service.getToken());
			} else {
				super.addErrorMessage(service.getMessage());
			}
		} catch (IOException e) {
			super.addErrorMessage("No fue posible conectarse con el servidor.");
		} catch (ParseException e) {
			super.addWarningMessage("Ocurrió un error al parsear la petición.");
		}
	}

	public String createUser() {
		if (newPassword.equals(newRepeatPassword)) {
			// TODO:Quitar hardcode
			newUsername = "aordonez";
			String encodedPwd = Utils.encryptPassword(newPassword);
			String encodedAnswer = Utils.encryptPassword(newAnswerQuestion);
			List<Object> portalUserData = new ArrayList<Object>();
			portalUserData.add(newFirstName);
			portalUserData.add(newLastName);
			portalUserData.add(newUser);
			portalUserData.add(encodedPwd);
			portalUserData.add(1);
			portalUserData.add(newEmail);
			portalUserData.add(newSecurityQuestion);
			portalUserData.add(encodedAnswer);
			portalUserData.add(newCompany);
			portalUserData.add(newUsername);
			portalUserData.add(1);
			portalUserData.add(newRol);
			createUpdatePortalUserRequest(Constantes.ISO003_NEW_PORTAL_USER,
					portalUserData);
		} else {
			super.addInfoMessage("Las contraseñas no coinciden");
		}
		return "";
	}

	public String updateUser() {
		// TODO:Quitar hardcode
		username = "aordonez";
		String encodedAnswer = currentItem.getAnswerQuestion();
		String encodedPwd = currentItem.getPassword();

		if (!password.equals(currentItem.getPassword()) && password != null) {
			encodedPwd = Utils.encryptPassword(password);
		}

		if (!answerQuestion.equals(currentItem.getAnswerQuestion())
				&& answerQuestion != null) {
			encodedAnswer = Utils.encryptPassword(answerQuestion);
		}
		List<Object> portalUserData = new ArrayList<Object>();
		portalUserData.add(firstName);
		portalUserData.add(lastName);
		portalUserData.add(user);
		portalUserData.add(encodedPwd);
		portalUserData.add(firstAccess);
		portalUserData.add(email);
		portalUserData.add(securityQuestion);
		portalUserData.add(encodedAnswer);
		portalUserData.add(company);
		portalUserData.add(username);
		portalUserData.add(isActive);
		portalUserData.add(rol);
		createUpdatePortalUserRequest(Constantes.ISO003_UPDATE_PORTAL_USER,
				portalUserData);
		return "";
	}

	public String deleteUser() {
		// TODO:Quitar hardcode
		username = "aordonez";
		List<Object> deletePortalUserData = new ArrayList<Object>();
		idPortalUser = currentItem.getIdPortalUser();
		deletePortalUserData.add(idPortalUser);
		deletePortalUserData.add(username);

		String deleteString = Utils.buildStringData(deletePortalUserData);
		try {
			BaseService service = new BaseService();
			service.setToken(currentToken);
			boolean response = service.isoMessageRequest(
					Constantes.ISO003_DELETE_PORTAL_USER,
					Constantes.DELETE_PORTAL_USER_METADATA, deleteString);
			if (response) {
				if (service.getToken().equals(currentToken)) {
					super.invalidateSession();
				} else {
					super.setTokenInContext(service.getToken());
				}
			} else {
				super.addErrorMessage(service.getMessage());
			}
		} catch (IOException e) {
			super.addErrorMessage("No fue posible conectarse con el servidor.");
		} catch (ParseException e) {
			super.addWarningMessage("Ocurrió un error al parsear la petición.");
		}
		return "";
	}

	public void createUpdatePortalUserRequest(String proccessingCode,
			List<Object> portalUserData) {
		String metadata = Constantes.CREATE_UPDATE_PORTAL_USER_METADATA;
		String string = Utils.buildStringData(portalUserData);
		try {
			BaseService service = new BaseService();
			service.setToken(currentToken);
			boolean response = service.isoMessageRequest(proccessingCode,
					metadata, string);
			if (response) {
				if (service.getToken().equals(currentToken)) {
					super.invalidateSession();
				} else {
					super.setTokenInContext(service.getToken());
				}
			} else {
				super.addErrorMessage(service.getMessage());
			}
		} catch (IOException e) {
			super.addErrorMessage("No fue posible conectarse con el servidor.");
		} catch (ParseException e) {
			super.addWarningMessage("Ocurrió un error al parsear la petición.");
		}
	}

	public void setValues(PortalUserDTO dto) {
		idPortalUser = dto.getIdPortalUser();
		firstName = dto.getFirstName();
		lastName = dto.getLastName();
		user = dto.getUser();
		password = dto.getPassword();
		firstAccess = dto.getFirstName();
		email = dto.getEmail();
		securityQuestion = dto.getSecurityQuestion();
		answerQuestion = dto.getAnswerQuestion();
		company = dto.getCompany();
		area = dto.getArea();
	}

	public long getIdPortalUser() {
		return idPortalUser;
	}

	public void setIdPortalUser(long idPortalUser) {
		this.idPortalUser = idPortalUser;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getNewPassword() {
		return newPassword;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}

	public String getRepeatPassword() {
		return repeatPassword;
	}

	public void setRepeatPassword(String repeatPassword) {
		this.repeatPassword = repeatPassword;
	}

	public String getFirstAccess() {
		return firstAccess;
	}

	public void setFirstAccess(String firstAccess) {
		this.firstAccess = firstAccess;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getSecurityQuestion() {
		return securityQuestion;
	}

	public void setSecurityQuestion(String securityQuestion) {
		this.securityQuestion = securityQuestion;
	}

	public String getAnswerQuestion() {
		return answerQuestion;
	}

	public void setAnswerQuestion(String answerQuestion) {
		this.answerQuestion = answerQuestion;
	}

	public String getCompany() {
		return company;
	}

	public void setCompany(String company) {
		this.company = company;
	}

	public String getArea() {
		return area;
	}

	public void setArea(String area) {
		this.area = area;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public int getIsActive() {
		return isActive;
	}

	public void setIsActive(int isActive) {
		this.isActive = isActive;
	}

	public String getRol() {
		return rol;
	}

	public void setRol(String rol) {
		this.rol = rol;
	}

	public PortalUserDTO getCurrentItem() {
		return currentItem;
	}

	public void setCurrentItem(PortalUserDTO currentItem) {
		setValues(currentItem);
		this.currentItem = currentItem;
	}

	public List<PortalUserDTO> getListItems() {
		init();
		return listItems;
	}

	public void setListItems(List<PortalUserDTO> listItems) {
		this.listItems = listItems;
	}

	public static Logger getLogger() {
		return LOGGER;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public String getCurrentToken() {
		return currentToken;
	}

	public void setCurrentToken(String currentToken) {
		this.currentToken = currentToken;
	}

	public String getNewIdPortalUser() {
		return newIdPortalUser;
	}

	public void setNewIdPortalUser(String newIdPortalUser) {
		this.newIdPortalUser = newIdPortalUser;
	}

	public String getNewFirstName() {
		return newFirstName;
	}

	public void setNewFirstName(String newFirstName) {
		this.newFirstName = newFirstName;
	}

	public String getNewLastName() {
		return newLastName;
	}

	public void setNewLastName(String newLastName) {
		this.newLastName = newLastName;
	}

	public String getNewUser() {
		return newUser;
	}

	public void setNewUser(String newUser) {
		this.newUser = newUser;
	}

	public String getNewEmail() {
		return newEmail;
	}

	public void setNewEmail(String newEmail) {
		this.newEmail = newEmail;
	}

	public String getNewSecurityQuestion() {
		return newSecurityQuestion;
	}

	public void setNewSecurityQuestion(String newSecurityQuestion) {
		this.newSecurityQuestion = newSecurityQuestion;
	}

	public String getNewAnswerQuestion() {
		return newAnswerQuestion;
	}

	public void setNewAnswerQuestion(String newAnswerQuestion) {
		this.newAnswerQuestion = newAnswerQuestion;
	}

	public String getNewCompany() {
		return newCompany;
	}

	public void setNewCompany(String newCompany) {
		this.newCompany = newCompany;
	}

	public String getNewArea() {
		return newArea;
	}

	public void setNewArea(String newArea) {
		this.newArea = newArea;
	}

	public String getNewUsername() {
		return newUsername;
	}

	public void setNewUsername(String newUsername) {
		this.newUsername = newUsername;
	}

	public Date getNewSaveData() {
		return newSaveData;
	}

	public void setNewSaveData(Date newSaveData) {
		this.newSaveData = newSaveData;
	}

	public int getNewIsActive() {
		return newIsActive;
	}

	public void setNewIsActive(int newIsActive) {
		this.newIsActive = newIsActive;
	}

	public String getNewRol() {
		return newRol;
	}

	public void setNewRol(String newRol) {
		this.newRol = newRol;
	}

	public String getPasswordChanged() {
		return passwordChanged;
	}

	public void setPasswordChanged(String passwordChanged) {
		this.passwordChanged = passwordChanged;
	}

	public String getNewRepeatPassword() {
		return newRepeatPassword;
	}

	public void setNewRepeatPassword(String newRepeatPassword) {
		this.newRepeatPassword = newRepeatPassword;
	}

	public String getNewFirstAcces() {
		return newFirstAcces;
	}

	public void setNewFirstAcces(String newFirstAcces) {
		this.newFirstAcces = newFirstAcces;
	}

}
